# -*- coding: utf-8 -*-

import os

from django.conf import settings
from django.core.management import BaseCommand

from common.log import logger
from common.management import BaseDataBaseManager


# ==============================================================================
# 数据库回滚实现示例
# ==============================================================================
class DefaultRollBack(BaseDataBaseManager):
    """
    迁移操作默认示例
    """

    @classmethod
    def rollback_tables(cls, database, tables, path):
        """
        回滚数据表
        """
        logger.info(f"starting rollback {database}")
        for table in tables:
            file_path = os.path.join(path, f"{table}.sql")
            command = (
                f"mysql -h {settings.DB_HOST} -P {settings.DB_PORT} "
                f"-u{settings.DB_USERNAME} -p{settings.DB_PASSWORD} {database} <{file_path}"
            )
            os.system(command)
            logger.info(f"rollback {database} {table} finish")
        logger.info(f"rollback {database} finish")


class Command(BaseCommand):
    def handle(self, *args, **options):

        # 回滚数据表
        DefaultRollBack.rollback_tables()
